import React, { useState, useEffect } from 'react';
import { 
  Box, 
  Heading, 
  Text, 
  Badge, 
  Spinner, 
  Tabs, 
  TabList, 
  TabPanels, 
  Tab, 
  TabPanel,
  Code,
  Divider,
  Flex,
  Spacer,
  Stat,
  StatLabel,
  StatNumber,
  Stack,
  HStack,
  useColorModeValue
} from '@chakra-ui/react';
import { getNodeDetail } from '../api/api';
import SyntaxHighlighter from 'react-syntax-highlighter';
import { docco } from 'react-syntax-highlighter/dist/esm/styles/hljs';

const NodeDetails = ({ nodeId }) => {
  const [nodeDetail, setNodeDetail] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const bgColor = useColorModeValue('white', 'gray.800');
  
  console.log("NodeDetails组件接收到的nodeId:", nodeId, "类型:", typeof nodeId);

  useEffect(() => {
    const fetchNodeDetail = async () => {
      if (!nodeId && nodeId !== 0 && nodeId !== '0') {
        console.log("nodeId为空或无效，不发送请求. nodeId:", nodeId);
        setNodeDetail(null);
        return;
      }
      
      // 确保传递字符串类型的ID
      const normalizedNodeId = String(nodeId);
      console.log("准备获取节点详情，nodeId:", normalizedNodeId);
      setLoading(true);
      setError(null);
      
      try {
        console.log("发送getNodeDetail请求，参数:", { node_id: normalizedNodeId });
        const detail = await getNodeDetail(normalizedNodeId);
        console.log("获取节点详情成功:", detail);
        setNodeDetail(detail);
      } catch (err) {
        console.error("获取节点详情失败:", err);
        setError(err.message || '获取节点详情失败');
      } finally {
        setLoading(false);
      }
    };
    
    fetchNodeDetail();
  }, [nodeId]);
  
  if (!nodeId && nodeId !== 0 && nodeId !== '0') {
    return (
      <Box p={5} shadow="md" borderWidth="1px" borderRadius="md" bg={bgColor} width="100%" height="400px">
        <Heading size="md" mb={4}>节点详情</Heading>
        <Text>请从树图中选择一个节点查看详情</Text>
      </Box>
    );
  }
  
  if (loading) {
    return (
      <Box p={5} shadow="md" borderWidth="1px" borderRadius="md" bg={bgColor} width="100%" height="400px" textAlign="center">
        <Heading size="md" mb={4}>节点详情</Heading>
        <Spinner mt={10} size="xl" />
        <Text mt={4}>加载节点详情...</Text>
      </Box>
    );
  }
  
  if (error) {
    return (
      <Box p={5} shadow="md" borderWidth="1px" borderRadius="md" bg={bgColor} width="100%" height="400px">
        <Heading size="md" mb={4}>节点详情</Heading>
        <Text color="red.500">错误: {error}</Text>
      </Box>
    );
  }
  
  if (!nodeDetail) {
    console.log("nodeDetail为空, 返回null");
    return null;
  }
  
  const { name, full_name, content, raw_properties } = nodeDetail;
  console.log("渲染节点详情:", { name, full_name });
  
  // 获取代码语言
  const getLanguage = () => {
    const extension = raw_properties.file_path ? raw_properties.file_path.split('.').pop() : '';
    
    switch(extension) {
      case 'java': return 'java';
      case 'py': return 'python';
      case 'js': return 'javascript';
      case 'ts': return 'typescript';
      case 'php': return 'php';
      case 'rb': return 'ruby';
      case 'go': return 'go';
      case 'cpp': 
      case 'c': return 'cpp';
      default: return 'java'; // 默认显示为Java
    }
  };
  
  return (
    <Box p={4} shadow="md" borderWidth="1px" borderRadius="md" bg={bgColor} width="100%" height="600px" overflowY="auto">
      <Heading size="md" mb={3}>节点详情</Heading>
      
      <Box mb={3}>
        <HStack wrap="wrap" spacing={2} mb={2}>
          <Badge colorScheme="blue">{raw_properties.type || 'function'}</Badge>
          {raw_properties.visibility && <Badge colorScheme="green">{raw_properties.visibility}</Badge>}
          {raw_properties.is_static && <Badge colorScheme="purple">static</Badge>}
          {raw_properties.is_constructor && <Badge colorScheme="orange">constructor</Badge>}
        </HStack>
        
        <Text fontWeight="bold" fontSize="lg">{name}</Text>
        <Text color="gray.600" fontSize="sm" noOfLines={1} title={full_name}>{full_name}</Text>
        <Text color="gray.400" fontSize="xs" mt={1}>节点ID: {nodeId}</Text>
      </Box>
      
      <Divider my={2} />
      
      <Stack direction={['column', 'row']} spacing={3} mb={3}>
        <Stat size="sm">
          <StatLabel>行范围</StatLabel>
          <StatNumber fontSize="md">{raw_properties.line_start || '-'} - {raw_properties.line_end || '-'}</StatNumber>
        </Stat>
        
        {raw_properties.complexity && (
          <Stat size="sm">
            <StatLabel>复杂度</StatLabel>
            <StatNumber fontSize="md">{raw_properties.complexity}</StatNumber>
          </Stat>
        )}
      </Stack>
      
      <Tabs variant="enclosed" size="sm" mt={3}>
        <TabList>
          <Tab>代码内容</Tab>
          <Tab>属性信息</Tab>
        </TabList>
        
        <TabPanels>
          <TabPanel p={2}>
            {content ? (
              <Box borderWidth="1px" borderRadius="md" overflow="hidden">
                <SyntaxHighlighter 
                  language={getLanguage()} 
                  style={docco}
                  customStyle={{margin: 0, maxHeight: '300px', fontSize: '12px'}}
                >
                  {content}
                </SyntaxHighlighter>
              </Box>
            ) : (
              <Text color="gray.500">无代码内容或解压失败</Text>
            )}
          </TabPanel>
          
          <TabPanel p={2}>
            <Box overflowX="auto">
              <pre>
                <Code p={2} borderRadius="md" fontSize="xs" width="100%">
                  {JSON.stringify(raw_properties, null, 2)}
                </Code>
              </pre>
            </Box>
          </TabPanel>
        </TabPanels>
      </Tabs>
    </Box>
  );
};

export default NodeDetails; 